<?php
/**
 * Gére les requetes et reponse de flux HTML 
 *
 * @copyright Copyright (c) 2013
 * @version   1.0
 * 
 * @todo commenter la classe
 **/
class ServiceController
{	
 	const actionParam  = 'act';
 	const JSON  = 'json';
 	const XML  = 'xml';
	const UNKOWN = '?';
 
	protected $_userMembership;
	protected $_actionCode;
	protected $_responseData;
	protected $_msg;
	protected $_params;
	protected $_debug;
	
    /**
    * Constructor
    * Ouvert ou prolonge la session
    * 
    * @return void
    */    
    public function __construct () {
		ob_start();
		session_start();
		$this->_userMembership = new Membership();
		$this->_isSecurePage = true;
		$this->_responseData =  NULL;
		$this->_debug = (isset($_GET['debug']))? ($_GET['debug'] == 'on') : false;
		$this->_params = array();
		$this->_msg = NULL;
    }
	
	public function writeTrace() {
		if ($this->_debug)
		{
			$numargs = func_num_args();
			$msg = '';
	     	if ($numargs == 1) 
				$msg = func_get_arg(0);
			elseif ($numargs > 1) 
				$msg = implode(" ", func_get_args());

			echo htmlentities ($msg) . "<BR/>";
		}
	}
	
	private function getHttpParam($code){
		$val = (isset($_GET[$code]))? $_GET[$code] : '';
		
		if (isset($_POST[$code]))
			$val = $_POST[$code];
		
		return $val;
	}
	
 	/**
	* Recupere Les paramètres passés en GET ou en POST
	* 
	*/
 	public function getParameters ( ) {
		$this->writeTrace("debut getParameters");
		
		$this->_actionCode = ucfirst(strtolower($this->getHttpParam(self::actionParam)));
		$this->writeTrace('getParameters:: actionCode =', $this->_actionCode);

		if (empty($this->_actionCode))
		{
			$this->_msg = "Code de l'action obligatoire";
			$this->badRequest();			
		}

		$this->writeTrace('getParameters:: parcours des variables GET');
		foreach($_GET as $key => $val) {
			$this->writeTrace('getParameters::    GET[', $key,'"]=',$val);
			$this->_params[$key] = $val;
		}

		$this->writeTrace('getParameters:: parcours des variables POST');
		foreach($_POST as $key => $val) {
			$this->writeTrace('getParameters::    POST[', $key,'"]=',$val);
			$this->_params[$key] = $val;
		}

	}
	
	public function getUserMembership() {
		return $this->_userMembership;
	}


	public function validateAuthorization( ) {
		$this->writeTrace("validateAuthorization");
		return ($this->_isSecurePage)? $this->validateAuthentication() : true;
	}


	/**
	* Retourne vrai si l'utilisateur a le droit d'accéder à 
	* cette page ou si la page est en accès libre.
	* 
	*/
	public function validateAuthentication ( ) {
		$this->writeTrace("validateAuthentication");	
			//use $this->_userMembership->getPermission();
		return $this->_userMembership->isAuthenticated();
	}
	
	/**
	* 
	*/
	public function getServiceType() {
		$this->writeTrace("getServiceType");	
		return self::JSON;		
	}

	/**
	* todo : récuparation de l'erreur d'execution du la classe de traitement
	*/
	public function execute() {
		$this->writeTrace("execute");	
		$className = 'Services\\'.$this->_actionCode.'Action';
		$this->writeTrace('class d\'action :', $className);	
		$action = NULL;
		if (class_exists($className)) {
			$this->writeTrace('La classe d\'action existe');	
			$action = new $className();
		} 
		else {
			$this->msg = 'Action inconnue';
			$this->writeTrace($this->msg);	
			$this->badRequest();			
		}
		
		if ($action != NULL)
			$this->_responseData = $action->execute($this, $this->_params);
	}	
	
	/**
	* 
	*/
	public function writeJsonResponse() {
		$this->writeTrace("writeJsonResponse");	
		$response = ($this->_responseData == NULL)? NULL : json_encode($this->_responseData);
		if ($this->_debug) {
			$this->writeTrace("<HR>Flux de reponse :");
			if ($response == NULL)
				$this->writeTrace("Vide (NULL)");			
			else
				$this->writeTrace($response);			
			$this->writeTrace("<HR>");
		} else {
			header('Content-type: application/json');
			echo $response;							
		}

	}

	/**
	* @todo A implementer
	*/
	public function writeXmlResponse() {
		$this->writeTrace("writeXmlResponse");	
		header('Content-type: text/xml');
		die("Not implemented");
	}
	
	public function badRequest() {
		$this->writeTrace("badRequest");	
		header('HTTP/1.0 400 Bad Request', true, 400);
		if ($this->_msg == NULL)
			echo 'Type du service inconnu';
		else
			echo $this->_msg;
		exit();
	}

	public function unauthorized() {
		$this->writeTrace("unauthorized");	
		header('HTTP/1.0 401 Unauthorized', true, 401);
		echo 'Vous n\'etes pas authentifié ou vous n\'avez pas le droit d\'acceder à ce service';
		exit();
	}

	public function end() {
		$this->writeTrace("end");	
	}
} // END class